<template>
  <div class="content-wrapper">
    <!-- 表格组件 -->
    <div class="table-wrapper">
      <AvicTable
        ref="demoSub"
        :bordered="false"
        table-key="demoSub"
        :columns="columns"
        :row-key="(record) => record.id"
        :data-source="list"
        :loading="loading"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          columnWidth: 40,
          fixed: true
        }"
        :custom-row="
          (record) => {
            return {
              onClick: () => {
                handleRowSelection(record);
              }
            };
          }
        "
        :show-custom-page-size="true"
        :page-parameter="queryParam.pageParameter"
        :total="totalPage"
        @change="handleTableChange"
        @refresh="getList"
      >
        <template #toolBarLeft>
          <a-space>
            <a-button v-hasPermi="['demoSub:add']" title="添加" type="primary" @click="handleAdd">
              <template #icon>
                <plus-outlined />
              </template>
              添加
            </a-button>
            <a-button
              v-hasPermi="['demoSub:delete']"
              title="删除"
              danger
              :type="selectedRowKeys.length == 0 ? 'default' : 'primary'"
              :loading="delLoading"
              @click="handleDelete(selectedRowKeys, '')"
            >
              <template #icon>
                <delete-outlined />
              </template>
              删除
            </a-button>
            <a-button v-hasPermi="['demoSub:import']" title="导入" type="primary" ghost @click="handleImport">
              <template #icon>
                <import-outlined />
              </template>
              导入
            </a-button>
            <a-button v-hasPermi="['demoSub:export']" title="导出" type="primary" ghost @click="handleExport">
              <template #icon>
                <export-outlined />
              </template>
              导出
            </a-button>
          </a-space>
        </template>
        <template #toolBarRight>
          <a-input-search
            class="opt-btn-commonsearch"
            style="width: 240px"
            placeholder="请输入必填或电话(正则)"
            title="请输入必填或电话(正则)"
            :allow-clear="true"
            @search="handleKeyWordQuery"
          />
        </template>
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'id'">
            <span :title="index + 1 + queryParam.pageParameter.rows * (queryParam.pageParameter.page - 1)">
              {{ index + 1 + queryParam.pageParameter.rows * (queryParam.pageParameter.page - 1) }}
            </span>
          </template>
          <template v-else-if="column.dataIndex === 'action'">
            <a-button type="link" class="inner-btn" @click.stop="handleEdit(record.id)">编辑</a-button>
            <a-button v-hasPermi="['demoSub:delete']" type="link" class="inner-btn" @click.stop="handleDelete([record.id], 'row')">
              删除
            </a-button>
          </template>
        </template>
      </AvicTable>
    </div>
    <!-- 添加页面弹窗 -->
    <demo-sub-add v-if="showAddModal" ref="addModal" :main-id="mainId" @reloadData="getList" @close="showAddModal = false" />
    <!-- 编辑页面弹窗 -->
    <demo-sub-edit
      v-if="showEditModal"
      ref="editModal"
      :main-id="mainId"
      :form-id="formId"
      @reloadData="getList"
      @close="showEditModal = false"
    />
    <AvicExcelImport
      v-if="showImportModal"
      :form-data="excelParams"
      title="单表模板导入"
      import-url="/demo/template/demosubs/import-data/v1"
      download-template-url="/demo/template/demosubs/download-template/v1"
      @reloadData="getList"
      @close="showImportModal = false"
    />
  </div>
</template>
<script lang="ts" setup>
// 引入模块API
import { listDemoSubByPage, delDemoSub, exportExcel } from '@/api/avic/demo/DemoSubApi';
// 引入添加页面组件
import DemoSubAdd from './DemoSubAdd.vue';
// 引入编辑页面组件
import DemoSubEdit from './DemoSubEdit.vue';
const { proxy } = getCurrentInstance();
const props = defineProps({
  // 主表选中项的keys集合
  mainId: {
    type: String,
    default: ''
  }
});
const columns = [
  {
    title: '序号',
    dataIndex: 'id',
    ellipsis: true,
    width: 60,
    align: 'center',
    fixed: 'left'
  },
  {
    title: '用户',
    dataIndex: 'demoUserIdAlias',
    ellipsis: true,
    width: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '部门',
    dataIndex: 'demoDeptIdAlias',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '角色',
    dataIndex: 'demoRoleIdAlias',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '群组',
    dataIndex: 'demoGroupIdAlias',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '岗位',
    dataIndex: 'demoPositionIdAlias',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '单选',
    dataIndex: 'demoRadioName',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '单选（按钮）',
    dataIndex: 'demoRadioButtonName',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '复选',
    dataIndex: 'demoCheckboxName',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '下拉',
    dataIndex: 'demoSelectName',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '下拉多选',
    dataIndex: 'demoSelectMultipleName',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '密级',
    dataIndex: 'secretLevelName',
    ellipsis: true,
    width: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '开关',
    dataIndex: 'demoSwitch',
    ellipsis: true,
    sorter: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '小数',
    dataIndex: 'demoNumber',
    ellipsis: true,
    width: 120,
    resizable: true,
    customRender: (text) => proxy.$formatZero(text.value, 2),
    align: 'right'
  },
  {
    title: '整数',
    dataIndex: 'demoInteger',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'right'
  },
  {
    title: '日期',
    dataIndex: 'demoDate',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '日期时间',
    dataIndex: 'demoDateTime',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '必填',
    dataIndex: 'demoNotnull',
    ellipsis: true,
    sorter: true,
    width: 120,
    resizable: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    align: 'left'
  },
  {
    title: '编码',
    dataIndex: 'demoCode',
    ellipsis: true,
    sorter: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '电话(正则)',
    dataIndex: 'demoPhone',
    ellipsis: true,
    width: 120,
    resizable: true,
    sorter: true,
    align: 'left'
  },
  {
    title: '邮箱(正则)',
    dataIndex: 'demoEmail',
    ellipsis: true,
    width: 120,
    resizable: true,
    sorter: true,
    align: 'left'
  },
  {
    title: '网址(正则)',
    dataIndex: 'demoWebsite',
    ellipsis: true,
    width: 120,
    resizable: true,
    sorter: true,
    align: 'left'
  },
  {
    title: '唯一值',
    dataIndex: 'demoUnique',
    ellipsis: true,
    customHeaderCell() {
      return {
        ['class']: 'required-table-title'
      };
    },
    width: 120,
    resizable: true,
    sorter: true,
    align: 'left'
  },
  {
    title: '弹窗',
    dataIndex: 'demoModalSelectAlias',
    ellipsis: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '多行文本',
    dataIndex: 'demoTextarea',
    ellipsis: true,
    minWidth: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '背景样式',
    dataIndex: 'demoBackgroundColor',
    ellipsis: true,
    sorter: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '测试文本',
    dataIndex: 'demoText2',
    ellipsis: true,
    sorter: true,
    width: 120,
    resizable: true,
    align: 'left'
  },
  {
    title: '操作',
    dataIndex: 'action',
    ellipsis: true,
    width: 120,
    fixed: 'right'
  }
];
const queryParam = reactive({
  // 请求表格数据参数
  pageParameter: {
    page: 1, // 页数
    rows: proxy.$settings.table.pageSize || 20 // 每页条数
  },
  searchParams: {
    demoMainId: ''
  },
  keyWord: ref(''), // 快速查询数据
  sidx: null, // 排序字段
  sord: null // 排序方式: desc降序 asc升序
});
const showAddModal = ref(false); // 是否展示添加弹窗
const showEditModal = ref(false); // 是否展示编辑弹窗
const showImportModal = ref(false); // 是否展示导入弹窗
const excelParams = ref({ tableName: 'demoSub', demoMainId: '' });
const list = ref([]); // 表格数据集合
const formId = ref(''); // 当前行数据id
const selectedRowKeys = ref([]); // 选中数据主键集合
const selectedRows = ref([]); // 选中行集合
const loading = ref(false);
const delLoading = ref(false);
const totalPage = ref(0);
onMounted(() => {
  // 重载子表数据
  getList();
});

/** 查询数据  */
function getList() {
  selectedRowKeys.value = []; // 清空选中
  selectedRows.value = [];
  list.value = [];
  loading.value = true;
  queryParam.searchParams.demoMainId = props.mainId ? props.mainId : '-1';
  listDemoSubByPage(queryParam)
    .then((response) => {
      list.value = response.data.result;
      totalPage.value = response.data.pageParameter.totalCount;
      queryParam.pageParameter.page = response.data.pageParameter.page;
      loading.value = false;
    })
    .catch(() => {
      list.value = [];
      totalPage.value = 0;
      loading.value = false;
    });
}
/** 快速查询逻辑 */
function handleKeyWordQuery(value) {
  queryParam.keyWord = value;
  queryParam.pageParameter.page = 1;
  getList();
}
/** 添加 */
function handleAdd() {
  if (props.mainId === '') {
    proxy.$message.warning('请选择一条主数据');
    return;
  }
  showAddModal.value = true;
}
/** 编辑 */
function handleEdit(id) {
  formId.value = id;
  showEditModal.value = true;
}
/* 子表删除 */
function handleDelete(ids, type) {
  if (ids.length === 0) {
    proxy.$message.warning('请选择要删除的数据！');
    return;
  }
  proxy.$confirm({
    title: `确认要删除${type === 'row' ? '当前行的' : '选择的'}数据吗?`,
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: () => {
      delLoading.value = true;
      delDemoSub(ids)
        .then((res) => {
          if (res.success) {
            proxy.$message.success('删除成功！');
            // 清空选中
            selectedRowKeys.value = [];
            selectedRows.value = [];
            getList();
          }
          delLoading.value = false;
        })
        .catch(() => {
          delLoading.value = false;
        });
    }
  });
}
/** 导入 */
function handleImport() {
  if (props.mainId === '') {
    proxy.$message.warning('请选择一条主数据');
    return;
  }
  excelParams.value.demoMainId = props.mainId;
  showImportModal.value = true;
}
/** 导出 */
function handleExport() {
  proxy.$confirm({
    title: '确认导出数据吗?',
    okText: '确定',
    cancelText: '取消',
    centered: true,
    onOk: () => {
      loading.value = true;
      exportExcel(queryParam).then(() => {
        loading.value = false;
        proxy.$message.info('导出成功');
      });
    }
  });
}
/** 勾选复选框时触发 */
function onSelectChange(rowKeys, rows) {
  selectedRowKeys.value = rowKeys;
  selectedRows.value = rows;
}
/** 表头排序 */
function handleTableChange(pagination, _filters, sorter) {
  queryParam.pageParameter.page = pagination.current;
  queryParam.pageParameter.rows = pagination.pageSize;
  if (proxy.$objIsNotBlank(sorter.field)) {
    queryParam.sidx = sorter.field;
    queryParam.sord = sorter.order === 'ascend' ? 'asc' : 'desc'; // 排序方式: desc降序 asc升序
  }
  getList();
}
/** 表格行选中 */
function handleRowSelection(record) {
  const selectIds = [...selectedRowKeys.value];
  // 多选
  if (!selectIds.includes(record.id)) {
    // 选中
    selectedRowKeys.value.push(record.id);
  } else {
    // 取消选中
    selectedRowKeys.value = selectedRowKeys.value.filter((item) => item !== record.id);
  }
}

watch(
  () => props.mainId,
  (newVal) => {
    if (newVal) {
      getList(); // 查询表格数据
    } else {
      selectedRowKeys.value = []; // 清空选中
      selectedRows.value = [];
      list.value = [];
      totalPage.value = 0;
    }
  },
  { immediate: true }
);
</script>
